package com.springboot.resttemplate.controller;

import com.springboot.resttemplate.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @GetMapping("/getUserByUsername")
    public User getUserById(@RequestParam("username") String username,
                            @RequestParam("address") String address,
                            @RequestHeader(value = "token",required = false) String token,
                            @CookieValue(value = "sa-token",required = false) String saToken
        ){
        log.info("username = {}, address = {}", username, address);
        User user = new User();
        user.setUsername(username);
        user.setAddress( address);
        log.info("token:{}",token);
        log.info("saToken:{}",saToken);
        return user;
    }

    @PostMapping("/insert")
    public String insertUser(@RequestBody User user,@RequestHeader("token") String token){
        log.info("user:{}",user);
        log.info("token:{}",token);
        return "success";
    }

    @PutMapping
    public String update(@RequestBody User user){
        log.info("user:{}",user);
        return "success";
    }

    @PostMapping("/upload")
    public String upload(MultipartFile file){
        return file.getOriginalFilename();
    }
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        File file = new File("D:\\test.txt");
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=test.txt");
        InputStream in = new FileInputStream(file);
        IOUtils.copy(in, response.getOutputStream());
    }

    @GetMapping("/retry")
    public String retry(){
        int timeout = (int)(Math.random()*5 + 5);
        try {
//            TimeUnit.SECONDS.sleep(timeout);
            Thread.sleep(timeout*1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }
}